<?php

namespace Utils\Service\Common;

use Utils\Service\Tencent\Image;

class Helper
{

    public static function array_recursive_merge($arr1, $arr2)
    {
        $ret = array_merge($arr1, $arr2);
        foreach ($ret as $key => $value) {
            if (is_array($value)) {
                $ret[$key] = self::array_recursive_merge(isset($arr1[$key]) ? $arr1[$key] : [], isset($arr2[$key]) ? $arr2[$key] : []);
            }
        }
        return $ret;
    }

    /**
     * 替换字符串中{varname}为对应的变量
     * @param string $subject
     * @param array $args 变量表
     * @return mixed
     */
    public static function var_replace($subject, $args)
    {
        if (preg_match_all('|\{(?<varname>[_A-Za-z][_A-Za-z0-9]*)\}|', $subject, $matches) >= 1) {
            foreach ($matches['varname'] as $varname) {
                if (isset($args[$varname])) {
                    $subject = str_replace('{' . $varname . '}', $args[$varname], $subject);
                }
            }
        }
        return $subject;
    }

    public static function slot($id, $slotSpace = 1024)
    {
        return crc32($id) % $slotSpace;
    }

    public static function array_key_convert(array $array, array $map, $keepUnmetioned = false, $allowMissing = true)
    {
        $ret = [];
        foreach ($map as $key => $dstKey) {
            if (isset($array[$key])) {
                $ret[$dstKey] = $array[$key];
                unset($array[$key]);
            } else if (!$allowMissing) {
                return false;
            }
        }
        if ($keepUnmetioned and !empty($array)) {
            $ret = array_merge($array, $ret);
        }
        return $ret;
    }

    public static function rebuildUrl($url, array $params, $host = NULL)
    {
        $components = parse_url($url);
        if ($params) {
            $oldParams = isset($components['query']) ? $components['query'] : '';
            parse_str($oldParams, $oldParams);
            $params = array_merge($oldParams, $params);
            $components['query'] = http_build_query($params);
        }
        empty($host) or $components['host'] = $host;
        $ret = "{$components['scheme']}://{$components['host']}";
        isset($components['path']) and $ret .= "{$components['path']}";
        isset($components['query']) and $ret .= "?{$components['query']}";
        isset($components['fragment']) and $ret .= "#{$components['fragment']}";
        return $ret;
    }

    /**
     * $str 原始中文字符串
     * $encoding 原始字符串的编码，默认GBK
     * $prefix 编码后的前缀，默认"&#"
     * $postfix 编码后的后缀，默认";"
     */
    public static function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';')
    {
        $str = iconv($encoding, 'UCS-2', $str);
        $arrstr = str_split($str, 2);
        $unistr = '';
        for ($i = 0, $len = count($arrstr); $i < $len; $i++) {
            $dec = hexdec(bin2hex($arrstr[$i]));
            $unistr .= $prefix . $dec . $postfix;
        }
        return $unistr;
    }

    /**
     * $str Unicode编码后的字符串
     * $decoding 原始字符串的编码，默认GBK
     * $prefix 编码字符串的前缀，默认"&#"
     * $postfix 编码字符串的后缀，默认";"
     */
    public static function unicode_decode($unistr, $encoding = 'GBK', $prefix = '&#', $postfix = ';')
    {
        $arruni = explode($prefix, $unistr);
        $unistr = '';
        for ($i = 1, $len = count($arruni); $i < $len; $i++) {
            if (strlen($postfix) > 0) {
                $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
            }
            $temp = intval($arruni[$i]);
            $unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
        }
        return iconv('UCS-2', $encoding, $unistr);
    }

    public static function characterToUTF8($data)
    {
        if (!empty($data)) {
            $fileType = mb_detect_encoding($data, array('UTF-8', 'GBK', 'LATIN1', 'BIG5'));
            if ($fileType != 'UTF-8') {
                $data = mb_convert_encoding($data, 'utf-8', $fileType);
            }
        }
        return $data;
    }

    public static function imageIDToUrl($id, $bucket)
    {
        return Image::makeDownloadUri($id, $bucket);
    }

}